package com.shanshi.activity;

import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.shanshi.activity.response.ResStoreInfo;
import com.shanshi.activity.tool.OkHttpTool;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class Suggest extends MainActivity implements OnItemSelectedListener{

	private SharedPreferences sharedPreferences;
	// 创建OkHttpClient实例
	private final OkHttpClient client = new OkHttpClient();
	private TextView tv;
	private ImageView img1;
	private ImageView img2;
	private ImageView img3;
	private Spinner mySpinner;
	private List<String> list = new ArrayList<>();
	private List<String> listdata = new ArrayList<>();
	private List<Integer> idlist = new ArrayList<>();//存放选择门店的id
	private ArrayAdapter<String> adapter;
	private String uri1="";
	private String uri2="";
	private String uri3="";
	private EditText mysuggest;
	private int lastActivity;//判断是由哪个页面跳转而来
	private int storeId = 0;//选择的店铺id
	private int userId = 0;//用户id
	private List<ResStoreInfo.Data> listStoreInfo;

	private Uri photoUri;
	private int i = 0;//控制选择的是第几张图片
	private boolean state1 = false; //是否选择第一张图片
	private boolean state2 = false; //是否选择第二张图片
	private boolean state3 = false; //是否选择第三张图片
	private ImageView suggest_close1; //删除按钮1
	private ImageView suggest_close2; //删除按钮2
	private ImageView suggest_close3; //删除按钮3
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub

		super.onCreate(savedInstanceState);
		setContentView(R.layout.suggest);

		//获得当前用户的id
		sharedPreferences = Suggest.this.getSharedPreferences("share", MODE_PRIVATE);
		userId = sharedPreferences.getInt("userId", 1);

		mySpinner = (Spinner) findViewById(R.id.spinner1);
		tv = (TextView) findViewById(R.id.title);
		tv.setText("投诉建议");
		img1 = (ImageView) findViewById(R.id.suggest_img1);
		img2 = (ImageView) findViewById(R.id.suggest_img2);
		img2.setVisibility(View.INVISIBLE);
		img3 = (ImageView) findViewById(R.id.suggest_img3);
		img3.setVisibility(View.INVISIBLE);

		suggest_close1 = (ImageView) findViewById(R.id.suggest_close1);
		suggest_close2 = (ImageView) findViewById(R.id.suggest_close2);
		suggest_close3 = (ImageView) findViewById(R.id.suggest_close3);

		mysuggest = (EditText) findViewById(R.id.mysuggest);
		lastActivity = getIntent().getIntExtra("lastActivity",1);
		if(lastActivity==1){
			mySpinner.setVisibility(View.GONE);
		}else if(lastActivity==2){
			getdatas();


			//数组适配器，将定义好的数据源加载到数组适配器中
			adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,listdata);
			//为适配器设置下拉列表下拉时的菜单样式
			adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
			//mySpinner加载适配器
			mySpinner.setAdapter(adapter);
			//给mySpinner设置监听器
			mySpinner.setOnItemSelectedListener(this);
		}

//		Iv.setOnClickListener(this);
		

		
		
	}
	
	/** 
	 * 本地上传图片 
	 * @author Administrator 
	 */  

	
	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
		//得到门店的id
		storeId = idlist.get(position);
	}
	@Override
	public void onNothingSelected(AdapterView<?> parent) {
		
		
	}
	
	public void nextPage(View view){
		Intent intent = null;
		switch (view.getId()) {
		case R.id.fanhui:
			   	finish();
			break;
		case R.id.suggest_submit:
			MultipartBody.Builder builder=  new MultipartBody.Builder().setType(MultipartBody.FORM);
		// 遍历map中所有参数到builder
			builder.addFormDataPart("userId", userId+"");
			builder.addFormDataPart("content", mysuggest.getText().toString());
			if(uri1!=""){
				builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"imgFiles\";filename=\"file.jpg\""), RequestBody.create(MediaType.parse("image/jpg"),new File(uri1)));
			}
			if(uri2!=""){
				builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"imgFiles\";filename=\"file.jpg\""), RequestBody.create(MediaType.parse("image/jpg"),new File(uri2)));
			}
			if(uri3!=""){
				builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"imgFiles\";filename=\"file.jpg\""), RequestBody.create(MediaType.parse("image/jpg"),new File(uri3)));
			}

			// 构建请求体
			// TODO: 2017/3/22
			//RequestBody requestBody = builder.build();
			RequestBody requestBody=builder.build();
			// 构建请求
			Request request = new Request.Builder()
					.url(OkHttpTool.BASE_URL+"stores/" + storeId + "/advice")// 地址
					.post(requestBody)// 添加请求体
					.build();

			// 发送异步请求，同步会报错，Android4.0以后禁止在主线程中进行耗时操作
			client.newCall(request).enqueue(new Callback() {

				@Override
				public void onFailure(Call arg0, IOException arg1) {
					// TODO Auto-generated method stub
					handler.sendEmptyMessage(3);
				}

				@Override
				public void onResponse(Call arg0, Response arg1) throws IOException {
					// TODO Auto-generated method stub
					handler.sendEmptyMessage(2);

				}
			});
			
			finish();
			
			
		break;
		//去到系统相册选择图片
		case R.id.suggest_img1:
			if(!state1){
				i=1;
				showBottomPopWindow();
			}else{
				intent = new Intent(this,ShowImgActivity.class);
				intent.putExtra("uri",uri1);
				startActivity(intent);
			}
		break;
		case R.id.suggest_img2:
			if(!state2){
				i=2;
				showBottomPopWindow();
			}else{
				intent = new Intent(this,ShowImgActivity.class);
				intent.putExtra("uri",uri2);
				startActivity(intent);
			}
		break;
		case R.id.suggest_img3:
			if(!state3){
				i=3;
				showBottomPopWindow();
			}else{
				intent = new Intent(this,ShowImgActivity.class);
				intent.putExtra("uri",uri3);
				startActivity(intent);
			}
		break;
			case R.id.suggest_close1:
				if(uri2!=""){
					uri1 = uri2;
					Glide.with(Suggest.this).load(uri1).centerCrop().into(img1);
					if(uri3!=""){
						state3 = false;
						uri2 = uri3;
						uri3="";
						Glide.with(Suggest.this).load(uri2).centerCrop().into(img2);
						suggest_close3.setVisibility(View.INVISIBLE);
						img3.setImageResource(R.drawable.celectphoto);
					}else{
						state2 = false;
						uri2="";
						img3.setVisibility(View.INVISIBLE);
						suggest_close2.setVisibility(View.INVISIBLE);
						img2.setImageResource(R.drawable.celectphoto);
					}
				}else{
					state1 = false;
					uri1="";
					img2.setVisibility(View.INVISIBLE);
					suggest_close1.setVisibility(View.INVISIBLE);
					img1.setImageResource(R.drawable.celectphoto);
				}
				break;
			case R.id.suggest_close2:
				if(uri3!=""){
					state3 = false;
					uri2 = uri3;
					uri3="";
					Glide.with(Suggest.this).load(uri2).centerCrop().into(img2);
					suggest_close3.setVisibility(View.INVISIBLE);
					img3.setImageResource(R.drawable.celectphoto);
				}else{
					state2 = false;
					uri2="";
					img3.setVisibility(View.INVISIBLE);
					suggest_close2.setVisibility(View.INVISIBLE);
					img2.setImageResource(R.drawable.celectphoto);
				}
				break;
			case R.id.suggest_close3:
				uri3="";
				suggest_close3.setVisibility(View.INVISIBLE);
				img3.setImageResource(R.drawable.celectphoto);
				state3 = false;
				break;
		}
	}
	
	
	/*************相册选择图片后回调方法*****************/
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_CANCELED) {
			return;
		}

		if(i==1){
			state1 = true;
			suggest_close1.setVisibility(View.VISIBLE);
		}else if(i==2){
			state2 = true;
			suggest_close2.setVisibility(View.VISIBLE);
		}else if(i==3){
			state3 = true;
			suggest_close3.setVisibility(View.VISIBLE);
		}

		//如果是相册
		if(requestCode<4){
			Log.d("MainActivity", 0 + "");
			Uri uri = data.getData();
			Log.d("uri", uri.toString());
			String[] pojo = { MediaStore.Images.Media.DATA };
			Cursor cursor = managedQuery(uri, pojo, null, null, null);
			if (cursor != null) {
				ContentResolver cr = this.getContentResolver();
				int colunm_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				cursor.moveToFirst();
				// 获取图片的路径
				String path = cursor.getString(colunm_index);
				/***
			 	* 这里加这样一个判断主要是为了第三方的软件选择，比如：使用第三方的文件管理器的话
			 	* ，你选择的文件就不一定是图片了，这样的话，我们判断文件的后缀名 如果是图片格式的话，那么才可以
			 	*/
				if (path.endsWith("jpg") || path.endsWith("png")) {
					if (requestCode == 1) {
						// 加载图片
						Glide.with(Suggest.this).load(uri).centerCrop().into(img1);
						uri1 = path;
						img2.setVisibility(View.VISIBLE);
					} else if (requestCode == 2) {
						Glide.with(Suggest.this).load(uri).centerCrop().into(img2);
						uri2 = path;
						img3.setVisibility(View.VISIBLE);
					} else if (requestCode == 3){
						Glide.with(Suggest.this).load(uri).centerCrop().into(img3);
						uri3 = path;
					}
				}
			}
		}else if(requestCode==4){
			//如果是相机
			uri1= pathFromPhoto();
			Glide.with(Suggest.this).load(uri1).centerCrop().into(img1);
			img2.setVisibility(View.VISIBLE);
		}else if(requestCode==5){
			uri2= pathFromPhoto();
			Glide.with(Suggest.this).load(uri2).centerCrop().into(img2);
			img3.setVisibility(View.VISIBLE);
		}else if(requestCode==6){
			uri3= pathFromPhoto();
			Glide.with(Suggest.this).load(uri3).centerCrop().into(img3);
		}

	}
	
	/***********获取店铺数据***********/
	public void getdatas(){
		Log.e("===aa","aaaaaaaa");
		OkHttpTool.doGet(OkHttpTool.BASE_URL + "stores?userId=0&pageIndex=0&pageSize=100&longitude=0&latitude=0", new OkHttpTool.setOkhttpListener() {
			@Override
			public void onSuccess(String s) {
				// TODO Auto-generated method stub
				Gson gson=new Gson();
				ResStoreInfo content=gson.fromJson(s, ResStoreInfo.class);
				Log.e("===dadaqq",content.toString());
				listStoreInfo = content.getData();
				Log.e("===dadaqq",content.toString());
				for(int i=0;i<listStoreInfo.size();i++){
					CItem cItem = new CItem(listStoreInfo.get(i).getStoreId(),listStoreInfo.get(i).getStoreName());
					list.add(cItem.toString());
					idlist.add(listStoreInfo.get(i).getStoreId());
				}
				handler.sendEmptyMessage(1);
			}

			@Override
			public void onFail() {
				Log.e("=========sa","sadfa");
			}
		});
//		OkHttpTool.doGet(OkHttpTool.BASE_URL+"stores?userId=0&pageIndex=0&pageSize=100&longitude=0&latitude=0"
//				, new setOkhttpListener() {
//
//			@Override
//			public void onSuccess(String s) {
//				// TODO Auto-generated method stub
//				Gson gson=new Gson();
//				ResStoreInfo content=gson.fromJson(s, ResStoreInfo.class);
//				Log.e("===dadaqq",content.toString());
//				listStoreInfo = content.getData();
//				Log.e("===dadaqq",content.toString());
//				for(int i=0;i<listStoreInfo.size();i++){
//					CItem cItem = new CItem(listStoreInfo.get(i).getStoreId(),listStoreInfo.get(i).getStoreName());
//					list.add(cItem.toString());
//					idlist.add(listStoreInfo.get(i).getStoreId());
//				}
//				handler.sendEmptyMessage(1);
//			}
//
//			@Override
//			public void onFail() {
//				// TODO Auto-generated method stub
//				Log.e("=========sa","sadfa");
//			}
//		});
		
	}
	Handler handler=new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
				case 1:
					listdata.addAll(list);
					adapter.notifyDataSetChanged();
					break;
				case 2:
					Toast.makeText(Suggest.this, "提交投诉建议成功", Toast.LENGTH_LONG).show();
					break;
				case 3:
					Toast.makeText(Suggest.this, "提交投诉建议失败", Toast.LENGTH_LONG).show();
					break;
			}
		}
	};
	
	public class CItem {

		 private int ID = 0;
		 private String Value = "";

		 public CItem () {
		  ID = 0;
		  Value = "";
		 }

		 public CItem (int _ID, String _Value) {
		  ID = _ID;
		  Value = _Value;
		 }

		 @Override
		 public String toString() {           //为什么要重写toString()呢？因为适配器在显示数据的时候，如果传入适配器的对象不是字符串的情况下，直接就使用对象.toString()
		  // TODO Auto-generated method stub
		  return Value;
		 }

		 public int GetID() {
		  return ID;
		 }

		 public String GetValue() {
		  return Value;
		 }  
		}


	/**
	 * 调用系统拍照
	 */
	public void photo(){

		Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		ContentValues values = new ContentValues();
		photoUri=this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);

		startActivityForResult(intent, i+3);
	}

	/**
	 * 从系统拍照获取图片路径
	 * @return
	 */
	private String pathFromPhoto() {

		String picPath=null;
		String[] pojo = {MediaStore.Images.Media.DATA};
		Cursor cursor = managedQuery(photoUri, pojo, null, null,null);
		if(cursor != null )
		{
			int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
			cursor.moveToFirst();
			picPath = cursor.getString(columnIndex);

			try {

				if(Integer.parseInt(Build.VERSION.SDK) <14){

					cursor.close();
				}

			} catch (NumberFormatException e) {

				Log.v("qin","error:"+e);
			}

		}
		return picPath;
	}


	/**自定义的底部弹窗***/
	public void showBottomPopWindow() {

		final AlertDialog mDialog = new AlertDialog.Builder(this).create();
		mDialog.show();
		Window window = mDialog.getWindow();
		window.setGravity(Gravity.BOTTOM);
		window.setWindowAnimations(R.style.popupAnimation);
		View view = View.inflate(this, R.layout.bottom_popwindow, null);
		TextView bd = (TextView) view.findViewById(R.id.dialog_bd);
		bd.setText("相册");
		TextView gd = (TextView) view.findViewById(R.id.dialog_gd);
		gd.setText("相机");
		TextView cancel = (TextView) view.findViewById(R.id.dialog_cancel);
		bd.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
//	            Toast.makeText(MainActivity.this, "mAdTv.getText():" + mAdTv.getText(), Toast.LENGTH_SHORT).show();
				mDialog.dismiss();
				Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            	startActivityForResult(intent, Suggest.this.i);
			}
		});
		gd.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
//	            Toast.makeText(MainActivity.this, "mSexTv.getText():" + mSexTv.getText(), Toast.LENGTH_SHORT).show();
				mDialog.dismiss();
				photo();
			}
		});
		cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
//	            Toast.makeText(MainActivity.this, "mSexTv.getText():" + mSexTv.getText(), Toast.LENGTH_SHORT).show();
				mDialog.dismiss();
			}
		});
		window.setContentView(view);
		window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);//设置横向全屏

		mDialog.setCanceledOnTouchOutside(false);
		mDialog.setCancelable(true);
	}
}
